package cn.exrick.xboot.base.serviceimpl

import cn.exrick.xboot.base.dto.BreakRolesRecordDto
import cn.exrick.xboot.base.entity.BreakRolesRecord
import cn.exrick.xboot.base.entity.Job
import cn.exrick.xboot.base.entity.JobAccidentCase
import cn.exrick.xboot.base.mapper.JobAccidentCaseMapper
import cn.exrick.xboot.base.service.*
import cn.exrick.xboot.base.vo.JobAccidentCaseDetailVo
import cn.exrick.xboot.base.vo.JobAccidentCaseListVo
import cn.exrick.xboot.core.common.utils.PageUtil
import cn.exrick.xboot.core.common.utils.ResultUtil
import cn.exrick.xboot.core.common.utils.SecurityUtil
import cn.exrick.xboot.core.common.utils.ToolUtil
import cn.exrick.xboot.core.common.vo.PageVo
import cn.exrick.xboot.core.common.vo.Result
import cn.exrick.xboot.core.service.UserService
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.google.common.collect.Maps
import lombok.extern.slf4j.Slf4j
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
 * 岗位事故案例接口实现
 * @author Fei
 */
@Slf4j
@Service
@Transactional
open class IJobAccidentCaseServiceImpl : ServiceImpl<JobAccidentCaseMapper?, JobAccidentCase?>(), IJobAccidentCaseService {


    @Autowired
    private lateinit var securityUtil: SecurityUtil

    @Autowired
    private lateinit var iEnterpriseUserService: IEnterpriseUserService

    @Autowired
    private lateinit var iJobService: IJobService

    @Autowired
    private lateinit var iAccidentCaseService: IAccidentCaseService

    @Autowired
    private lateinit var iEnterpriseEmployeeService: IEnterpriseEmployeeService

    @Autowired
    private lateinit var userService: UserService

    override fun createOrUpdateJobAccidentCase(jobAccidentCase: JobAccidentCase): Result<Any?>? {

        return try {

            if (ToolUtil.isNotEmpty(getOne(KtQueryWrapper(JobAccidentCase::class.java).eq(JobAccidentCase::accidentCaseId, jobAccidentCase.accidentCaseId)
                            .eq(JobAccidentCase::jobId, jobAccidentCase.jobId)))) {

                return ResultUtil.error(203, "该事故案例已经跟当前岗位绑定!")
            }

            jobAccidentCase.enterpriseUserId = iJobService.getById(jobAccidentCase.jobId)?.enterpriseId
            saveOrUpdate(jobAccidentCase)
            ResultUtil.success("操作成功")
        } catch (e: Exception) {

            ResultUtil.error(e.message)
        }
    }

    override fun getJobAccidentByEnterpriseId(pageVo: PageVo, jobId: String, enterpriseId: String): Result<MutableMap<String, Any?>>? {

        return ToolUtil.setListToNul(list(KtQueryWrapper(JobAccidentCase::class.java)
                .eq(JobAccidentCase::enterpriseUserId, enterpriseId)
                .eq(ToolUtil.isNotEmpty(jobId), JobAccidentCase::jobId, jobId)
                .orderByDesc(JobAccidentCase::createTime)))?.run {

            val result: MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = size
            result["content"] = PageUtil.listToPage(pageVo, mapNotNull { getJobAccidentCaseListVo(it?.id) }.toMutableList())

            ResultUtil.data(result, "获取我岗位的事故案例成功")
        } ?: ResultUtil.error(201, "暂无数据！")
    }

    override fun removeJobAccidentCase(ids: Array<out String>): Result<Any?>? {

        return try {

            removeByIds(ids.toList())
            ResultUtil.success("操作成功！")
        } catch (e: Exception) {

            ResultUtil.error(e.message)
        }
    }

    override fun getJobAccidentCaseList(breakRolesRecordDto: BreakRolesRecordDto, pageVo: PageVo): Result<MutableMap<String, Any?>>? {

        val jobAccidentCaseWrapper = KtQueryWrapper(JobAccidentCase::class.java)
                .eq(JobAccidentCase::createBy, securityUtil.currUser.id)
                .orderByDesc(BreakRolesRecord::createTime)
        if (ToolUtil.isNotEmpty(breakRolesRecordDto.enterpriseUserId)) jobAccidentCaseWrapper.eq(JobAccidentCase::enterpriseUserId,
                breakRolesRecordDto.enterpriseUserId)
        if (ToolUtil.isNotEmpty(breakRolesRecordDto.jobId)) jobAccidentCaseWrapper.eq(JobAccidentCase::jobId, breakRolesRecordDto.jobId)

        return ToolUtil.setListToNul(list(jobAccidentCaseWrapper))?.run {


            var data = mapNotNull { getJobAccidentCaseListVo(it?.id) }
            if (ToolUtil.isNotEmpty(breakRolesRecordDto.accidentCaseType))
                data = data.filter { it.accidentCaseType == breakRolesRecordDto.accidentCaseType }

            if (ToolUtil.isEmpty(data)) {

                return ResultUtil.error(201, "暂无数据")
            }

            val result: MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = size
            result["content"] = PageUtil.listToPage(pageVo, data)

            ResultUtil.data(result, "获取违章数据成功！")
        } ?: ResultUtil.error(201, "暂无数据！")
    }

    /**
     * 获取封装类
     */
    private fun getJobAccidentCaseListVo(id: String?): JobAccidentCaseListVo? {

        return getById(id)?.run {

            JobAccidentCaseListVo().apply {

                enterpriseName = iEnterpriseUserService.getEnterpriseNameById(enterpriseUserId)
                jobName = this@run.jobId?.let { iJobService.getJobName(it) }


                iAccidentCaseService.getById(accidentCaseId)?.let {

                    createName = userService.get(it.createBy)?.nickname
                    ToolUtil.copyProperties(it, this)
                    accidentCasePicLimitOne = it.pics?.split(",")?.get(0)
                    accidentSituation = enterpriseName.plus("在").plus(it.time).plus("发生").plus(it.accidentCaseType).plus("类型的事故,")
                            .plus("事故发生地点是:").plus(it.site).plus(",发生时间是:").plus(it.time).plus("死亡人数:").plus(it.deathToll).plus("受伤人数是:")
                            .plus(it.injuryNum)
                }
                ToolUtil.copyProperties(this@run, this)

            }
        }
    }

    override fun getJobAccidentCaseDetail(id: String?): Result<JobAccidentCaseDetailVo>? {

        return getById(id)?.run {

            ResultUtil.data(JobAccidentCaseDetailVo().apply {

                jobAccidentCaseListVo = getJobAccidentCaseListVo(id)
                ToolUtil.copyProperties(this@run, this)
                picList = iAccidentCaseService.getById(accidentCaseId)?.pics?.split(",")
            }, "获取详情成功")
        } ?: ResultUtil.error(201, "不存在此数据！")
    }

    override fun getJobAccidentCase(pageVo: PageVo): Result<MutableMap<String, Any?>>? {

        return ToolUtil.setListToNul(list(KtQueryWrapper(JobAccidentCase::class.java).eq(JobAccidentCase::jobId,
                iEnterpriseEmployeeService.getJobIdByEmployeeId(securityUtil.currUser.id))
                .orderByDesc(BreakRolesRecord::createTime)))?.run {

            val result: MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = size
            result["content"] = PageUtil.listToPage(pageVo, mapNotNull { getJobAccidentCaseListVo(it?.id) }.toMutableList())

            ResultUtil.data(result, "获取我岗位的事故案例成功")
        } ?: ResultUtil.error(201, "暂无数据！")

    }


}